/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 */

package com.examples;

import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;

import java.util.HashMap;
import java.util.Map;

public class ConfigurableEvent implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        for (PropertySource<?> propertySource : propertySources) {
            String name = propertySource.getName();
            boolean applicationConfig = name.contains("application.properties");
            if (!applicationConfig) {
                continue;
            }
            MapPropertySource mapPropertySource = (MapPropertySource) propertySource;
            Map<String, Object> source = mapPropertySource.getSource();
            Map<String, Object> map = new HashMap<>();
            source.forEach((k, v) -> map.put(k, v));
            // 设置支持动态添加配置项
            map.put("jodconverter.local.enabled", true);
            OriginTrackedMapPropertySource newMap = new OriginTrackedMapPropertySource(name, map);
            environment.getPropertySources().replace(name, newMap);
        }
    }
}
